package com.powermgr.boringtest.utils;

import java.util.*;
import java.text.*;
import java.io.*;
import java.net.*;

import lombok.extern.log4j.Log4j2;
import org.springframework.boot.configurationprocessor.json.JSONArray;
import org.springframework.boot.configurationprocessor.json.JSONObject;

import static com.powermgr.boringtest.utils.ConfigUtils.DAILY;

/**
 * DailyUtils
 *
 * @author qiuxiangdong
 * @date 2023/11/21 11:19
 */
@Log4j2
public class DailyUtils {
    private static String dailyUrl = null;
    public static void getDaily() {
        log.info("*开始执行下载" + DAILY + "分支");
        getUrl(0);
        if (dailyUrl == null){
            log.error("找不到最新的日构建版本");
        } else {
            download(dailyUrl, "version.tar.gz", DAILY);
            FileZipUtils.unTarGz(DAILY + File.separator + "version.tar.gz", DAILY);
            log.info("*" + DAILY + "分支测试用例下载完成");
        }
    }
    private static void getUrl(int day_args) {
        try {
            JSONObject one_payloadData = new JSONObject();
            one_payloadData.put("pageNum", 1);
            one_payloadData.put("pageSize", 1000);
            String startTime = new SimpleDateFormat("yyyyMMdd").format(new Date(System.currentTimeMillis() + (long) day_args * 24 * 60 * 60 * 1000)) + "000000";
            one_payloadData.put("startTime", startTime);
            one_payloadData.put("endTime", "");
            one_payloadData.put("projectName", "openharmony");
            one_payloadData.put("branch", "master");
            one_payloadData.put("component", "dayu200");
            one_payloadData.put("deviceLevel", "");
            one_payloadData.put("hardwareBoard", "");
            one_payloadData.put("buildStatus", "");
            one_payloadData.put("buildFailReason", "");
            one_payloadData.put("testResult", "");
            String postUrl = "http://ci.openharmony.cn/api/ci-backend/ci-portal/v1/dailybuilds";
            URL url = new URL(postUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setDoOutput(true);
            OutputStream os = conn.getOutputStream();
            os.write(one_payloadData.toString().getBytes("UTF-8"));
            os.flush();
            os.close();
            int statusCode = conn.getResponseCode();
            if (statusCode == 200) {
                InputStream inputStream = conn.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    response.append(line);
                }
                bufferedReader.close();
                inputStream.close();
                JSONObject result = new JSONObject(response.toString()).getJSONObject("result");
                JSONArray dailyBuildVos = result.getJSONArray("dailyBuildVos");
                String parent_url = "http://download.ci.openharmony.cn/";
                Map<Long, String> temp_dict = new LinkedHashMap<>();
                for (int i = 0; i < dailyBuildVos.length(); i++) {
                    JSONObject build = dailyBuildVos.getJSONObject(i);
                    String build_state = build.optString("buildSuccess");
                    if ("true".equals(build_state)) {
                        String get_create_time = build.optString("buildStartTime");
                        long get_create_time_int = new SimpleDateFormat("yyyyMMddHHmmss").parse(get_create_time).getTime() / 1000;
                        String request_url = parent_url + build.optString("obsPath");
                        temp_dict.put(get_create_time_int, request_url);
                    }
                }
                if (!temp_dict.isEmpty()) {
                    Map<Long, String> res_dict = sortKey(temp_dict, true);
                    dailyUrl = res_dict.entrySet().iterator().next().getValue();
                    log.info("最新的每日构建下载地址为：" + dailyUrl);
                } else {
                    day_args--;
                    if (day_args == -20) {
                        log.error("每日构建没有成功的版本");
                    } else {
                        getUrl(day_args);
                    }
                }
            }
        } catch (Exception e) {
            log.error(e);
        }
    }

    private static Map<Long, String> sortKey(Map<Long, String> old_dict, boolean reverse) {
        List<Long> keys = new ArrayList<>(old_dict.keySet());
        keys.sort(reverse ? Collections.reverseOrder() : null);
        Map<Long, String> new_dict = new LinkedHashMap<>();
        for (Long key : keys) {
            new_dict.put(key, old_dict.get(key));
        }
        return new_dict;
    }
    private static void download(String downloadUrl, String name, String path) {
        log.info("*开始下载: " + path + File.separator + name);
        try {
            long bytesum = 0;
            int byteread = 0;
            URL url = new URL(downloadUrl);
            URLConnection conn = url.openConnection();
            long contentLength = (conn.getContentLengthLong() / 1024) / 1024;
            log.info("*下载文件总大小: " + contentLength + "Mb");
            InputStream inStream = conn.getInputStream();
            FileOutputStream fs = new FileOutputStream(path + File.separator + name);
            byte[] buffer = new byte[1024];
            long len = 0;
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread;
                fs.write(buffer, 0, byteread);
                long x = (bytesum / 1024) / 1024;
                if (len != x) {
                    if (x % 100 == 0) {
                        log.info("文件大小: " + contentLength + "Mb，已下载：" + x + "Mb");
                    }
                }
                len = x;
            }
            log.info("文件大小: " + contentLength + "Mb，已下载：" + contentLength + "Mb");
        } catch (IOException e) {
            log.error("*download 错误 重新下载",e);
            download(downloadUrl,name,path);
        }
    }
}